package com.icesoft.core.web.configurer;

import com.icesoft.core.web.base.BaseHandlerInterceptor;
import com.icesoft.core.web.suppose.param.StringToEnumConverterFactory;
import com.icesoft.core.web.suppose.token.filter.AuthTokenArgumentResolver;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.format.FormatterRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Component
@Slf4j
@ServletComponentScan("com.icesoft")
@AllArgsConstructor
public class GlobeCommonConfigureAdapter implements WebMvcConfigurer {
    private final List<BaseHandlerInterceptor> interceptors;

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new StringToEnumConverterFactory());
    }

    /**
     * 配置拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (interceptors != null) {
            interceptors.forEach(interceptor -> {
                String[] patten = interceptor.pathPatten().split(",");
                InterceptorRegistration registration = registry.addInterceptor(interceptor).addPathPatterns(patten);
                List<String> excludePathPatterns = interceptor.excludePathPatterns();
                if (excludePathPatterns != null) {
                    registration.addPathPatterns(excludePathPatterns);
                }
                if (log.isInfoEnabled()) {
                    log.info("映射：{}，过滤器{}", patten, interceptor.getClass().getName());
                }
            });
        }

    }


    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new AuthTokenArgumentResolver());
    }
}
